﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management.Instrumentation;
using System.Runtime.InteropServices;

namespace 手机网络控制
{

    public partial class Form1 : Form
    {
        private string wifi_state = "UNKONWN";
        private Process proc = null;

        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }

        [DllImportAttribute("user32.dll", EntryPoint = "RegisterHotKey")]
        public static extern bool RegisterHotKey
            (
            IntPtr hwnd,        //要注册热键的窗口句柄      
            int hotkey_id,             //热键编号      
            int keyModifiers,    //特殊键如：Ctrl，Alt，Shift，Window      
            int key              //一般键如：A B C F1，F2 等      
            );


        [DllImportAttribute("user32.dll", EntryPoint = "UnregisterHotKey")]
        public static extern bool UnregisterHotKey
            (
                IntPtr hWnd,        //注册热键的窗口句柄      
                int id              //热键编号上面注册热键的编号      
            );

        public Form1()
        {
            proc = new Process();
            InitializeComponent();
        }
        public string RunCmd(string cmd)
        {
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            proc.StandardInput.WriteLine(cmd +"&exit");
            string outStr = proc.StandardOutput.ReadToEnd();
            proc.Close();
            outStr = outStr.Substring(outStr.IndexOf(cmd + "&exit")+cmd.Length+6);
            return outStr;
        }
        private string get_state()
        {
            string state_str = RunCmd("adb shell \"netcfg | grep wlan0\"");
            if (state_str != string.Empty)
            {
                if (state_str.IndexOf("UP") != -1)
                {
                    return "UP";
                } 
                else if (state_str.IndexOf("DOWN") != -1)
                {
                    return "DOWN";
                }
                return "UNKNOWN";
            }
            else
            {
                return "UNKNOWN";
            }
        }

        private void set_wifi_state(string new_state)
        {
            RunCmd(string.Format("adb shell \" svc wifi {0} \"", new_state));
        }

        private void wifi_reverse()
        {
            switch (wifi_state)
            {
                case "UP":
                    {
                        set_wifi_state("disable");
                        break;
                    }
                case "DOWN":
                    {
                        set_wifi_state("enable");
                        break;
                    }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            wifi_reverse();
        }

        private int timer_counter = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer_counter++;
            string devices = RunCmd("adb devices -l");
            string model = "";
            string serial_num = "";
            timer1.Enabled = false;
            int dev_num = 0;
            foreach (string dev in devices.Split('\n'))
            {
                if(dev.Length>10 && dev.IndexOf("List") <0)
                {
                    dev_num++;
                    model = dev.Substring(dev.IndexOf("model:") + 6,dev.IndexOf("device:")- dev.IndexOf("model:") - 6);
                    serial_num = dev.Substring(0,dev.IndexOf(" "));
                    break;
                }
            }
            if(dev_num==0)
            {
                toolStripStatusLabel1.Text = "没有连接Android设备";
            }
            else
            {
                toolStripStatusLabel1.Text = "当前设备:" + model;
            }
            wifi_state = get_state();
            switch (wifi_state)
            {
                case "UP":
                    {
                        button1.BackgroundImage = 手机网络控制.Properties.Resources.wifi_up;
                        notifyIcon1.Icon = 手机网络控制.Properties.Resources.ico_wifi_up;
                        toolStripStatusLabel2.Text = "手机wifi已开启";
                        break;
                    }
                case "DOWN":
                    {
                        button1.BackgroundImage = 手机网络控制.Properties.Resources.wifi_down;
                        notifyIcon1.Icon = 手机网络控制.Properties.Resources.ico_wifi_down;
                        toolStripStatusLabel2.Text = "手机wifi已经关闭";
                        break;
                    }
                case "UNKONWN":
                    {
                        button1.BackgroundImage = 手机网络控制.Properties.Resources.wifi_unknown;
                        notifyIcon1.Icon = 手机网络控制.Properties.Resources.ico_wifi_unknown;
                        toolStripStatusLabel2.Text = "手机wifi状态未知";
                        break;
                    }
            }
            if(timer_counter%10==0)
            {
                timer_counter = 0;
                RunCmd("adb shell svc data disable");
            }
            timer1.Enabled = true;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked==true)
            {
                string[] keys = textBox1.Text.Split('+');
                byte[] kecode = System.Text.Encoding.ASCII.GetBytes(keys[2]);
                RegisterHotKey(this.Handle,100,(int)(KeyModifiers.Ctrl|KeyModifiers.Shift),(int)kecode[0]);
            }
            else
            {
                UnregisterHotKey(this.Handle, 100);
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if((e.KeyChar >=65 && e.KeyChar <= 90 )||(e.KeyChar>=97 && e.KeyChar<=122))
            {
                textBox1.Text = "Ctrl+Shift+"+ e.KeyChar.ToString().ToUpper();
                if(checkBox1.Checked)
                {
                    byte[] kecode = System.Text.Encoding.ASCII.GetBytes(e.KeyChar.ToString().ToUpper());
                    UnregisterHotKey(this.Handle, 100);
                    RegisterHotKey(this.Handle, 100, (int)(KeyModifiers.Ctrl | KeyModifiers.Shift), (int)kecode[0]);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string cmd_str = RunCmd("adb version");
            if (cmd_str.IndexOf("Android Debug Bridge version")==-1)
            {
                MessageBox.Show("请正确安装ADB");
                Process.GetCurrentProcess().Kill();
            }
            RegisterHotKey(this.Handle, 100, (int)(KeyModifiers.Ctrl | KeyModifiers.Shift),(int)Keys.X);
            //载入任务栏右下角图标
            notifyIcon1.Icon = 手机网络控制.Properties.Resources.ico_wifi_unknown;
        }
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键 
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:    //按下的是Shift+S
                            //MessageBox.Show("快捷键触发!");    //此处填写快捷键响应代码     
                            wifi_reverse();
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗口退出时,取消全局热键的注册
            UnregisterHotKey(this.Handle, 100);
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //单击任务栏小图标
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

    }
}
